//
//  HMailListViewController.m
//  SCM
//
//  Created by Zhen Huang on 17/5/8.
//  Copyright © 2017年 huangzhen. All rights reserved.
//

#import "HMailListViewController.h"
#import <AFNetworking.h>
#import "Networking.h"
#import "MiSearchBar.h"
#import "HMailListModel.h"
#import "InitDbTable.h"
#import "HMailListTableViewCell.h"
#import "HmailListDetalViewController.h"
@interface HMailListViewController ()
<UITableViewDelegate,
UITableViewDataSource,
UITextFieldDelegate>
@property (nonatomic,assign)BOOL isSearch;
@property (nonatomic,strong)UITableView *tabelView;
@property (nonatomic,strong)NSMutableArray *dataArray;
@property (nonatomic,strong)UITextField *textField;
@property (nonatomic,strong)MiSearchBar *searchBar;
@property (nonatomic,strong)UIButton *dismissButton;
@property (nonatomic,strong)UIButton *searchButton;
@property (nonatomic,strong)NSMutableArray *indexArray;
@property (nonatomic,strong)NSMutableArray *textArray;
@property (nonatomic,strong)NSMutableArray *letterArray;
@property (nonatomic,strong)NSMutableArray *modelArray;

@end

@implementation HMailListViewController

- (instancetype)init
{
    if (self) {
        self.dataArray = [NSMutableArray new];
        self.indexArray = [NSMutableArray new];
        self.textArray = [NSMutableArray new];
        self.letterArray = [NSMutableArray new];
        self.modelArray = [NSMutableArray new];
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBar.hidden = NO;
    self.navigationController.navigationBar.barTintColor =kNavBlueColor;
    self.navigationController.navigationBar.titleTextAttributes = @{NSFontAttributeName:[UIFont systemFontOfSize:18],NSForegroundColorAttributeName:[UIColor whiteColor]};
    [self.view addSubview:self.searchBar];
    [self.view addSubview:self.tabelView];
    [self.view addSubview:self.dismissButton];
    [self setUpsearch];
    [self setSqlit];
}
- (void)setSqlit
{
    InitDbTable *manager = [[InitDbTable alloc]init];
    [InitDbTable sharedFMDBManeger];
    //调用打开数据库方法
    NSArray *array = [manager AllContacts];
    self.dataArray = (NSMutableArray *)array;
    NSArray *AZArray = @[@"A",@"B",@"C",@"D",@"E",@"F",@"G",@"H",@"I",@"J",@"K",@"L",@"M",@"N",@"O",@"P",@"Q",@"R",@"S",@"T",@"U",@"V",@"W",@"X",@"Y",@"Z"];
    NSMutableArray *letterArray = [NSMutableArray new];
    for (NSString *letter in AZArray) {
        NSMutableArray *modelArray = [NSMutableArray new];
        for (HMailListModel *model in array) {
            if ([letter isEqualToString:[model.INPUT_CODE1 substringToIndex:1]]) {
                [modelArray addObject:model];
                if (![letterArray containsObject:[model.INPUT_CODE1 substringToIndex:1]]) {
                    [letterArray addObject:letter];
                }
            }
        }
        [self.modelArray addObject: modelArray];
    }
    self.letterArray = letterArray;
    [self.tabelView reloadData];
}
- (UITableView *)tabelView
{
    if (!_tabelView) {
        _tabelView = [[UITableView alloc]initWithFrame:CGRectMake(0, NavBarHeight + 45, ScreenWidth, ScreenHeight- NavBarHeight - 45) style:UITableViewStyleGrouped];
        _tabelView.dataSource = self;
        _tabelView.delegate = self;
        [_tabelView registerClass:[HMailListTableViewCell class] forCellReuseIdentifier:@"cell"];
    
    }
    return _tabelView;
}
//生成右侧索引
- (void)setUpsearch
{
    
    for(char c = 'A'; c <= 'Z'; c++)
    {
        [self.indexArray addObject:[NSString stringWithFormat:@"%c",c]];
        [self.textArray addObject:[NSString stringWithFormat:@"%c",c]];
        [self.textArray addObject:[NSString stringWithFormat:@"%c",c]];
    }
}
//返回索引数组
-(NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView{
    
    return self.letterArray;
}

//响应点击索引时的委托方法
-(NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index{
    
    
    NSInteger count = 0;
    
    for (NSString *character in self.letterArray) {
        
        
        if ([[character uppercaseString] hasPrefix:title]) {
            return count;
        }
        
        count++;
    }
    
    return  0;
}
//返回每个索引的内容
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    
    return [self.indexArray objectAtIndex:section];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSArray *array = self.modelArray[section];
   return  array.count;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    return nil;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return CGFLOAT_MIN;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    HMailListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    NSArray *array = self.modelArray[indexPath.section];
    HMailListModel *model = array[indexPath.row];
    cell.nameLabel.text = model.EMP_NAME;
    return cell;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.letterArray.count;
}
- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    UIView *headerView = [[UIView alloc]init];
    headerView.backgroundColor = RGB(240, 241, 244);
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(12, 0, ScreenWidth, 26)];
    if (self.isSearch == YES) {
        label.text = @"";
    }else {
        label.text = self.letterArray[section];
    }
    [headerView addSubview:label];
    UIView *line = [[UIView alloc]initWithFrame:CGRectMake(0, 26-0.5, ScreenWidth, 0.5)];
    line.backgroundColor = RGB(224, 224, 224);
    [headerView addSubview:line];
    return headerView;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 26;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSArray *array = self.modelArray[indexPath.section];
    HMailListModel *model = array[indexPath.row];
    HmailListDetalViewController *HMailVC = [[HmailListDetalViewController alloc]initWithName:model.EMP_NAME?:@"" job_num:model.JUB_NUM?:@"" mobile_num:model.MOBILE_PHONE?:@"" address:model.ADDRESS?:@""];
    HMailVC.hidesBottomBarWhenPushed = YES;
    HMailVC.title = @"人员信息";
    [self.navigationController pushViewController:HMailVC animated:YES];
}
- (MiSearchBar *)searchBar
{
    if (!_searchBar) {
        _searchBar = [[MiSearchBar alloc]initWithFrame:CGRectMake(5, NavBarHeight + 10, ScreenWidth - 40, 30) placeholder:@"    请输入关键字"];
        _searchBar.delegate = self;
        _searchBar.barTintColor = [UIColor redColor];
        _searchBar.searchTextField.adjustsFontSizeToFitWidth = YES;
    }
    return _searchBar;
}
- (UIButton *)dismissButton
{
    if (!_dismissButton) {
        _dismissButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_dismissButton setTitle:@"取消" forState:UIControlStateNormal];
        _dismissButton.titleLabel.font = [UIFont systemFontOfSize:14];
        [_dismissButton setTitleColor:kNavBlueColor forState:UIControlStateNormal];
        _dismissButton.frame = CGRectMake(ScreenWidth - 35, NavBarHeight + 10,30 , 30);
        [_dismissButton addTarget:self action:@selector(handleYes:) forControlEvents:UIControlEventTouchUpInside];

    }
    return _dismissButton;
}
- (void)handleYes:(UIButton *)sender
{
    self.isSearch = NO;
    [self.letterArray removeAllObjects];
    [self.modelArray removeAllObjects];
    self.searchBar.text = @"";
    [self setSqlit];
}
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    self.isSearch = YES;
    if (searchText == 0) {
        [self.letterArray removeAllObjects];
        [self.modelArray removeAllObjects];
    }
    if (searchText > 0) {
        NSMutableArray *Array = [NSMutableArray new];
        NSMutableArray *newArray = [NSMutableArray new];
        for (NSArray *modelsArray in self.modelArray) {
            for (HMailListModel *model in modelsArray) {
                if (([model.EMP_NAME rangeOfString:searchText].location != NSNotFound) || ([model.INPUT_CODE1 rangeOfString:searchText].location != NSNotFound)) {
                    [Array addObject:model];
                    [self.letterArray removeAllObjects];
                    [self.letterArray addObject:[model.INPUT_CODE1 substringToIndex:1]];
                }
            }
        }
        if (Array.count != 0) {
            [newArray addObject:Array];
            self.modelArray = newArray;
        }
        [self.tabelView reloadData];
    }
}
-(BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    return YES;
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
